package com.tianquan.miracle.postprocessor;/**
 * @author starsea
 * @date 2024-09-30 上午9:18
 */

import com.tianquan.miracle.annotation.Bean;
import com.tianquan.miracle.util.MiracleUtils;

import java.lang.reflect.Method;

/**
 * @BelongsProject: uploaddemo
 * @BelongsPackage: com.tianquan.miracle.postprocessor
 * @Author: tianquan
 * @CreateTime: 2024-09-30  09:18
 * @Description: 解析@Bean注解,将方法返回值注册到容器中
 * @Version: 1.0
 */
public class InstanceBeanPostProcessor implements InjectBeanPostProcessor {

    public void inject(Object bean) {
        Class<?> aClass = bean.getClass();
        Method[] declaredMethods = aClass.getDeclaredMethods();
        for (Method method : declaredMethods) {
            Bean instance = method.getAnnotation(Bean.class);
            if (instance == null) continue;
            method.setAccessible(true);
            // 遍历拿到要入参要的Bean
            int parameterCount = method.getParameterCount();
            Class<?>[] parameterTypes = method.getParameterTypes();
            Object[] args = new Object[parameterCount];
            for (int i = 0; i < parameterCount; i++) {
                args[i] = MiracleUtils.getBean(parameterTypes[i]);
                if (args[i] == null) throw new RuntimeException("can not find bean is " + parameterTypes[i].getName());
            }
            try {
                // 调用方法,拿到要注入的对象
                Object object = method.invoke(bean, args);
                // 获取方法返回类型生成bean的名字,注册到容器中
                Class<?> returnType = method.getReturnType();
                String beanName = MiracleUtils.createBeanName(returnType);
                MiracleUtils.registerBean(beanName, object);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}
